const Redis = require('redis')
const Model = require('redis-crud-fork')
const config = require('config')
const {createClient} = require("webdav")
const UserCache = Model(Redis.createClient(Object.assign({db: 5}, config.get('redis'))), 'User')
const crypto = require('./utils/crypto')
const nc = require('./utils/nc')
const jwt = require('jsonwebtoken')
const clientKey = config.get('clientKey')
const nextcloud = config.get('nextcloud')
const shareFolder = config.get('nextcloud.share_path')
const webdav_path = `/remote.php/dav`;
const ShareCache = Model(Redis.createClient(Object.assign({db:4},config.get('redis'))),'Share')
import {getFileContent,getShareByPath,addShareLink} from './utils/nc/index'

const migrateShare = async ()=>{
    let users,user,webdavClient,file,files,id,share
    users = await UserCache.findAll()
    for(user of users){
        try{
            user.passwd = crypto.decrypt(user.passwd)
            webdavClient = createClient(
                `${nextcloud.host}${webdav_path}/files/${user.id}`,
                {username:user.id, password:user.passwd}
            )
            files = await webdavClient.getDirectoryContents(shareFolder,{glob: "/**/*.pub" })
            for(file of files){
                try{
                    share = await getShareByPath(user,shareFolder + '/' + file.basename)
                    id = share&&share.token
                    if(!id) {
                        share = await addShareLink(user, shareFolder + '/' + file.basename)
                        console.log(`publish ${file.basename} for user ${user.id} success`)
                    } 
                }catch(err){
                    console.log(`publish ${file.basename} for user ${user.id} error:` + err.stack||err)
                }
            }
            console.log(`migrate user ${user.id} success`)
        }catch(err){
            console.log(`migrate user ${user.id} error:` + err.stack||err)
        }
    }
}

const getLegacyShare = async(id)=>{
    let token,user,sharePath,client,data
    try{
        token = id.split(':::')[0],
        user = jwt.verify(token,clientKey)
        user.passwd = crypto.decrypt(user.passwd)
        sharePath = shareFolder + '/' + id.split(':::')[1]
        client = createClient(
            `${nextcloud.host}${webdav_path}`,
            {username: user.phone, password: user.passwd}
        );
        data = await getFileContent(client,`/files/${user.id}${sharePath}.pub`)
    }catch (e) {
        data = await ShareCache.get(id)
        data = data&&data.data
    }
    return data
}

module.exports = {migrateShare,getLegacyShare}

if (require.main === module) {
    migrateShare().then(() => {
            console.log('data migrate finished');
            process.exit(0);
        }
    ).catch((err) => {
        console.log(err)
    })
}


